﻿using System;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using LsTool;
using LsTool.ApiModels;
using Newtonsoft.Json;

namespace Zapi.Api.Filters
{
    /// <summary>
    /// 最先运行的Filter，被用作请求权限校验
    /// </summary>
    public class RoleAttribute : ActionFilterAttribute
    {


        /// <summary>
        /// 需要的权限
        /// </summary>
        /// <param name="rp"></param>
        public RoleAttribute(int rp) : this()
        {
            Rp = rp;
        }
        /// <summary>
        /// 需要的权限
        /// </summary>
        public RoleAttribute()
        {
            Rp = 0;
        }
        /// <summary>
        /// 需要的权限
        /// </summary>
        public int Rp { get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //是否通过
            bool isRole = false;
            var mu = HttpContext.Current.Request.Headers["token"];
            string[] rpList = {""};
            if (Rp == 0 )
            {
                isRole = true;
            }
            else
            {
                //var rpList = mu.Sys_ManagerRole.RolePowerList.Split('|');
                if (rpList.Any(a => Convert.ToInt32(a) == this.Rp))
                {
                    isRole = true;
                }
            }

            // 跳转
            if (!isRole)
            {
                var reModel = JsonConvert.SerializeObject(new ErrorOut($"没有权限({Rp})") { Code = "3" });
                //没权限
                actionContext.Response = new MyMessage(reModel);
            }
        }
    }
}